package com.cowmooed.service.impl;

import com.aliyun.imageseg20191230.Client;
import com.aliyun.imageseg20191230.models.SegmentHDCommonImageAdvanceRequest;
import com.aliyun.imageseg20191230.models.SegmentHDCommonImageResponse;
import com.aliyun.oss.OSS;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaModel;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.Common;
import com.aliyun.teautil.models.RuntimeOptions;
import com.aliyun.viapi20230117.models.GetAsyncJobResultRequest;
import com.aliyun.viapi20230117.models.GetAsyncJobResultResponse;
import com.cowmooed.properties.AliyunOssProperties;
import com.cowmooed.properties.AliyunViapiProperties;
import com.cowmooed.service.AliyunSdkHDSplitService;
import com.cowmooed.utils.ImageValidationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 阿里云SDK通用高清分割服务实现类
 * 实现使用阿里云视觉智能平台官方SDK进行通用高清分割功能
 */
@Service
public class AliyunSdkHDSplitServiceImpl implements AliyunSdkHDSplitService {

    @Autowired
    private AliyunViapiProperties aliyunViapiProperties;
    
    @Autowired
    private ResourceLoader resourceLoader;
    
    @Autowired
    private OSS ossClient;
    
    @Autowired
    private AliyunOssProperties aliyunOssProperties;

    /**
     * 创建阿里云imageseg客户端
     *
     * @return 阿里云imageseg客户端实例
     * @throws Exception 创建客户端异常
     */
    private Client createImageSegClient() throws Exception {
        Config config = new Config()
                .setAccessKeyId(aliyunViapiProperties.getAccessKeyId())
                .setAccessKeySecret(aliyunViapiProperties.getAccessKeySecret());
        config.endpoint = aliyunViapiProperties.getEndpoint();
        return new Client(config);
    }

    /**
     * 创建阿里云viapi客户端
     *
     * @return 阿里云viapi客户端实例
     * @throws Exception 创建客户端异常
     */
    private com.aliyun.viapi20230117.Client createViapiClient() throws Exception {
        Config config = new Config()
                .setAccessKeyId(aliyunViapiProperties.getAccessKeyId())
                .setAccessKeySecret(aliyunViapiProperties.getAccessKeySecret());
        config.endpoint = "viapi.cn-shanghai.aliyuncs.com";
        return new com.aliyun.viapi20230117.Client(config);
    }

    /**
     * 执行通用高清分割任务（使用官方SDK）
     *
     * @param imageUrl 待处理的图片路径或URL
     * @return 任务ID，用于后续查询结果
     */
    @Override
    public String submitUniversalHDSplitTaskBySdk(String imageUrl, String Action) {
        try {
            // 获取文件输入流
            InputStream inputStream = getInputStreamFromPathOrUrl(imageUrl);

            // 创建客户端
            Client client = createImageSegClient();

            // 构建请求参数
            SegmentHDCommonImageAdvanceRequest request = new SegmentHDCommonImageAdvanceRequest()
                    .setImageUrlObject(inputStream);

            // 设置运行时选项
            RuntimeOptions runtime = new RuntimeOptions();

            // 调用API
            SegmentHDCommonImageResponse response = client.segmentHDCommonImageAdvance(request, runtime);

            // 解析响应，获取任务ID
            String responseBody = Common.toJSONString(TeaModel.buildMap(response));

            return extractTaskIdFromResponse(responseBody);
        } catch (TeaException e) {
            // 处理阿里云SDK异常
            throw new RuntimeException("阿里云SDK调用异常: " + e.getMessage(), e);
        } catch (IOException e) {
            // 处理文件读取异常
            throw new RuntimeException("文件读取失败: " + e.getMessage(), e);
        } catch (Exception e) {
            // 处理其他异常
            throw new RuntimeException("提交分割任务失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 根据路径或URL获取输入流
     * @param pathOrUrl 文件路径或URL
     * @return 文件输入流
     * @throws IOException 输入输出异常
     */
    private InputStream getInputStreamFromPathOrUrl(String pathOrUrl) throws IOException {
        // 验证URL地址是否包含中文字符
        ImageValidationUtil.validateUrl(pathOrUrl);
        
        // 判断是否为远程URL
        if (pathOrUrl.startsWith("http://") || pathOrUrl.startsWith("https://")) {
            // 判断是否为阿里云OSS URL
            String ossEndpoint = aliyunOssProperties.getEndpoint();
            String ossBucketName = aliyunOssProperties.getBucketName();
            String ossUrlPrefix = "https://" + ossBucketName + "." + ossEndpoint + "/";
            
            if (pathOrUrl.startsWith(ossUrlPrefix)) {
                // 阿里云OSS URL，使用OSS客户端获取
                String objectKey = pathOrUrl.substring(ossUrlPrefix.length());
                return ossClient.getObject(ossBucketName, objectKey).getObjectContent();
            } else {
                // 其他远程URL，直接通过URL连接获取
                URL url = new URL(pathOrUrl);
                return url.openStream();
            }
        } else {
            // 本地文件路径
            Resource resource = resourceLoader.getResource(pathOrUrl);
            File file = resource.getFile();
            // 验证图像文件是否符合要求
            ImageValidationUtil.validateImage(file);
            return java.nio.file.Files.newInputStream(file.toPath());
        }
    }

    /**
     * 查询通用高清分割任务结果（使用官方SDK）
     *
     * @param taskId 任务ID
     * @return 包含任务状态和结果的Map
     */
    @Override
    public Map<String, Object> getUniversalHDSplitResultBySdk(String taskId,String Action) {
        try {
            // 创建客户端
            com.aliyun.viapi20230117.Client client = createViapiClient();

            // 构建请求参数
            GetAsyncJobResultRequest request = new GetAsyncJobResultRequest()
                    .setJobId(taskId);

            // 设置运行时选项
            RuntimeOptions runtime = new RuntimeOptions();

            // 调用API
            GetAsyncJobResultResponse response = client.getAsyncJobResultWithOptions(request, runtime);

            // 获取响应内容
            String responseBody = Common.toJSONString(TeaModel.buildMap(response));

            return processJobResult(responseBody);
        } catch (TeaException e) {
            // 处理阿里云SDK异常
            throw new RuntimeException("阿里云SDK调用异常: " + e.getMessage(), e);
        } catch (Exception e) {
            // 处理其他异常
            throw new RuntimeException("查询任务结果失败: " + e.getMessage(), e);
        }
    }

    /**
     * 从响应中提取任务ID
     * 根据阿里云API的返回结构进行解析，只返回RequestId
     */
    private String extractTaskIdFromResponse(String responseBody) {
        try {
            // 解析响应JSON
            com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(responseBody);

            // 从body中直接提取RequestId
            if (jsonObject.containsKey("body") && jsonObject.getJSONObject("body").containsKey("RequestId")) {
                return jsonObject.getJSONObject("body").getString("RequestId");
            }

            // 兼容旧的响应格式
            if (jsonObject.containsKey("body") && jsonObject.getJSONObject("body").containsKey("Data")) {
                com.alibaba.fastjson.JSONObject data = jsonObject.getJSONObject("body").getJSONObject("Data");
                if (data.containsKey("TaskId")) {
                    return data.getString("TaskId");
                }
            }

            // 如果无法提取RequestId或TaskId，返回空字符串
            return "";
        } catch (Exception e) {
            // 解析异常时返回空字符串
            return "";
        }
    }

    /**
     * 处理任务结果
     * 根据阿里云API的返回结构进行解析
     */
    private Map<String, Object> processJobResult(String responseBody) {
        // 解析响应JSON
        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(responseBody);
        Map<String, Object> result = new HashMap<>();

        // 根据阿里云viapi API的响应结构处理结果
        if (jsonObject.containsKey("body") && jsonObject.getJSONObject("body").containsKey("Data")) {
            com.alibaba.fastjson.JSONObject data = jsonObject.getJSONObject("body").getJSONObject("Data");

            // 获取任务状态
            String status = data.getString("Status");
            result.put("status", status);

            // 处理Result字段 - 可能是JSON对象或JSON字符串
            if (data.containsKey("Result")) {
                Object resultObj = data.get("Result");
                if (resultObj instanceof String) {
                    // 如果Result是字符串，尝试解析为JSON
                    try {
                        com.alibaba.fastjson.JSONObject resultJson = com.alibaba.fastjson.JSONObject.parseObject((String) resultObj);
                        if (resultJson.containsKey("imageUrl")) {
                            String imageUrl = resultJson.getString("imageUrl");
                            // 验证URL地址是否包含中文字符
                            ImageValidationUtil.validateUrl(imageUrl);
                            result.put("url", imageUrl);
                            return result;
                        }
                    } catch (Exception e) {
                        // 解析失败时，将原始字符串添加到结果中
                        result.put("rawResult", resultObj);
                    }
                } else if (resultObj instanceof com.alibaba.fastjson.JSONObject && ((com.alibaba.fastjson.JSONObject) resultObj).containsKey("imageUrl")) {
                    // 如果Result是JSONObject且包含imageUrl
                    String imageUrl = ((com.alibaba.fastjson.JSONObject) resultObj).getString("imageUrl");
                    // 验证URL地址是否包含中文字符
                    ImageValidationUtil.validateUrl(imageUrl);
                    result.put("url", imageUrl);
                    return result;
                }
            }
        }
        return result;
    }
}